package com.sleet.yuemiao.comment;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: yuemiao
 * @ClassName StaticPageInitCotroller
 * @description:
 * @author: Liyongxing
 * @create: 2021-12-07 20:02
 **/
@Slf4j
@Component
public class StaticPageInitController implements ApplicationListener<ContextRefreshedEvent> {
    private static Map<String, ControllerInfoEntity> infos = new HashMap<>();
    public static ControllerInfoEntity getInfos(String key) {
        return infos.get(key);
    }
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        log.info("静态页服务开始");
        try {
            Map<String, Object> controller = SpringUtils.getApplicationContext()
                    .getBeansWithAnnotation(ControllerInfo.class);
            controller.forEach((key, val) -> {
                for (Method method : val.getClass().getMethods()) {
                    ControllerMapping[] ems = method.getDeclaredAnnotationsByType(ControllerMapping.class);
                    if (ems != null && ems.length > 0) {
                        ControllerMapping em = ems[0];
                        ControllerInfoEntity eie = new ControllerInfoEntity();
                        eie.setBeanName(key);
                        eie.setMethodName(method.getName());
                        eie.setParameterTypes(method.getParameterTypes());
                        String serviceKey = String.format("%s:%s", em.scene(), em.mapping());

                        infos.put(serviceKey, eie);
                        log.info("静态页服务：{},{}", serviceKey, eie);
                    }
                }
            });
            log.info("静态页服务完成");
        } catch (Exception e) {
            log.error("静态页服务失败", e);
        }
    }
}
